package com.AAL.DAO;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.classic.Session;

import com.AAL.DAO.Interface.IReportDAO;
import com.AAL.Model.Employee;
import com.AAL.Model.Report;
import com.AAL.Model.TypesOfReport;
import com.AAL.Utils.HibernateUtil;

public class ReportDAO implements IReportDAO {

	@Override
	public Report saveAndUpdateReport(Report report) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try {
			session.saveOrUpdate(report);
		} catch (Exception e) {
			return null;
		}
		session.getTransaction().commit();
		return report;
	}

	@Override
	public Report deleteReport(int reportID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.beginTransaction();
			Report report = (Report) session.load(Report.class, reportID);
			if (null != report) {
				session.delete(report);
			}
			session.getTransaction().commit();
			return report;
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
			return null;
		}
	}

	@Override
	public Report getReport(int reportID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Report report = (Report) session.load(Report.class, reportID);
		return report;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Report> getLstReportsByTypeOfReport(TypesOfReport type) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Report> lstReports = null;
		try {
			lstReports = (List<Report>) session
					.createQuery(
							"from Report where typesOfReport.typeOfReportID=:typeOfReportID")
					.setParameter("typeOfReportID", type.getTypeOfReportID())
					.list();
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return lstReports;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Report> getLstReportsByEmployee(Employee employee) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Report> lstReports = null;
		try {
			lstReports = (List<Report>) session
					.createQuery(
							"from Report where employee.employeeID=:employeeID")
					.setParameter("employeeID", employee.getEmployeeID())
					.list();
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return lstReports;
	}

}
